package com.mk.web.dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mk.web.dao.CUserDao;
import com.mk.web.model.CUser;

/**
 * Created by WangChen on 2018/11/26 20:11.
 */
public class CUserDaoImpl implements CUserDao {

    @Override
    public CUser getByName(String name) {
        CUser user = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 声明链接并获得链接
            connection = DriverManager.getConnection(
                    "jdbc:mysql://192.168.52.134:3306/mktest",
                    "wangchen",
                    "wangchen@123");
            // 声明sql
            String sql = "select * from cuser where name = ?";
            // 声明sql处理
            preparedStatement = connection.prepareStatement(sql);
            // 添加参数
            preparedStatement.setString(1, name);
            // 执行获取结果
            preparedStatement.execute();
            resultSet = preparedStatement.getResultSet();
            while (resultSet.next()){
                user = new CUser();
                user.setId(resultSet.getInt(1));
                user.setName(resultSet.getString(2));
                user.setAge(resultSet.getInt(3));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                resultSet.close();
                preparedStatement.close();
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return user;
    }
}
